package com.hongye.house.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.hongye.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hongye.common.utils.PageUtils;
import com.hongye.common.utils.Query;

import com.hongye.house.dao.CityHomeDao;
import com.hongye.house.entity.CityHomeEntity;
import com.hongye.house.service.CityHomeService;


@Service("cityHomeService")
public class CityHomeServiceImpl extends ServiceImpl<CityHomeDao, CityHomeEntity> implements CityHomeService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CityHomeEntity> page = this.page(
                new Query<CityHomeEntity>().getPage(params),
                new QueryWrapper<CityHomeEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CityHomeEntity> selchild() {
        if (redisTemplate.opsForValue().get("CityList")!=null){
            Object child = redisTemplate.opsForValue().get("CityList");
            String s = JSONObject.toJSONString(child);
            List<CityHomeEntity> cityHomeEntities = JSONObject.parseObject(s, new TypeReference<List<CityHomeEntity>>() {
            });
            return cityHomeEntities;
        }

        List<CityHomeEntity> cid = this.baseMapper.selectList(new QueryWrapper<CityHomeEntity>().eq("cid", 0));
        //一级列表进递归
        dg(cid);
        redisTemplate.opsForValue().set("CityList",cid);
        return cid;
    }
    private void dg(List<CityHomeEntity> citylist){

        //遍历一级列表。
        for (CityHomeEntity cityHomeEntity : citylist) {
            //通过一级列表的id，查询二级列表
            List<CityHomeEntity> cid = this.baseMapper.selectList(new QueryWrapper<CityHomeEntity>().eq("cid", cityHomeEntity.getPid()));
            //判断二级列表是否有对象，有递归，无则继续循环
            if (cid!=null){
                cityHomeEntity.setListCity(cid);
                dg(cid);
            }

        }

    }

}